import React, { Component } from 'react'
import { Card, Button, message, Form, Input, Spin, Popconfirm, Cascader } from 'antd'
import { withRouter, RouteComponentProps } from 'react-router-dom'
import { queryManufacturer, modifyManufacturer } from '../../../requests/Manufacturer'
import { Store, ValidateErrorEntity } from 'rc-field-form/lib/interface'
import { FormInstance } from 'antd/lib/form'
import ManufacturerInfo from '../../../types/ManufacturerInfo'
import { getRes } from "../../../configFile";
import { district } from '../../../static/district/distrcit2'
const { TextArea } = Input


interface IProps extends RouteComponentProps<{ id: string }> { }
interface IState {
    manuID: number
    isLoading: boolean
    manuInfo: ManufacturerInfo | undefined
    districtSource: Array<object>
}
class SpecificModifyManu extends Component<IProps, IState> {
    constructor(props: IProps) {
        super(props)
        this.state = {
            districtSource: district,
            isLoading: true,
            manuID: Number.parseInt(this.props.match.params.id),
            manuInfo: undefined
        }
    }
    //创建Form引用
    formRef = React.createRef<FormInstance>()

    //模态框样式
    modalLayout = {
        labelCol: { span: 2 },
        wrapperCol: { span: 22 },
    }
    tailLayout = {
        wrapperCol: { offset: 2 },
    };

    //是否是二级地址
    ifDirect = (code: string) => {
        return ['81', '82', '11', '12', '31', '50'].includes(code.slice(0, 2));
    }

    componentDidMount = async () => {
        try {
            const res = getRes(await queryManufacturer(this.state.manuID))
            if (res.isSuccessful === true) {
                this.setState({
                    ...this.state,
                    manuInfo: res.data
                })
                //设置表单域    实例不为空
                if (this.formRef.current) {
                    this.formRef.current.setFieldsValue(res.data);
                    //设置地区
                    let codeArr = [];
                    if (this.ifDirect(res.data.manufacturerAddress.split(',')[0])) {
                        //直辖市
                        codeArr = [0, 0, 2];
                    } else {
                        codeArr = [0, 1, 2];
                    }
                    let area: string[] = [];
                    codeArr.forEach(i => {
                        let str: string = res.data.manufacturerAddress.split(',')[0].slice(0, 2 + 2 * i);
                        for (let j = 0; j < 4 - 2 * i; j++) {
                            str = str + '0'
                        }
                        console.log('str', str);
                        area.push(str);
                    })

                    this.formRef.current.setFieldsValue({
                        area: area
                    })
                    this.formRef.current.setFieldsValue({ specificAddr: res.data.manufacturerAddress.split(',').pop() });
                }

            } else {
                message.error(res.message)
            }
            this.setState({
                ...this.state,
                isLoading: false
            })
        } catch (err) {
            message.error(err.toString())
        }
    }

    //放弃修改
    modifyAbort = () => {
        this.props.history.goBack()
    }

    //提交失败
    onFinishFailed = (errorInfo: ValidateErrorEntity) => {
        message.error(errorInfo.errorFields[0].errors[0]);
    };


    //提交成功
    onFinish: (values: Store) => void = async values => {
        const paraTmp: ManufacturerInfo = {
            manufacturerID: this.state.manuID,
            manufacturerName: values.manufacturerName,
            manufacturerAddress: values.area.slice(-1) + ',' + values.specificAddr,     //注意slice返回的是Array
            manufacturerIntroduction: values.manufacturerIntroduction,
            manufacturerTelephone: values.manufacturerTelephone
        }

        this.setState({
            ...this.state,
            isLoading: true
        })
        try {
            const res = getRes(await modifyManufacturer(paraTmp))
            if (res.isSuccessful === true) {
                message.success("修改成功")
                this.props.history.goBack()
            } else {
                message.error("修改失败")
            }

        } catch (err) {
            message.error(err.toString())
        } finally {
            this.setState({
                ...this.state,
                isLoading: false
            })
        }
    }

    render() {
        return (
            <Spin spinning={this.state.isLoading}>
                <Card
                    extra={<Popconfirm
                        placement="topRight"
                        title='确定放弃更改吗？'
                        onConfirm={this.modifyAbort}
                        okText="确定"
                        cancelText="取消"
                    >
                        <Button danger>放弃更改</Button>
                    </Popconfirm>}
                    title={this.state.manuInfo?.manufacturerName}
                >
                    <Form
                        onFinishFailed={this.onFinishFailed}
                        onFinish={this.onFinish}
                        ref={this.formRef}
                        {...this.modalLayout}
                        name="manufacturerModify"
                        hideRequiredMark
                    >

                        <Form.Item
                            name="manufacturerName"
                            label="厂商名称"
                            rules={[
                                {
                                    required: true,
                                    message: '厂商名称必填',
                                },
                            ]}
                            hasFeedback
                        >
                            <Input />
                        </Form.Item>

                        <Form.Item
                            name="manufacturerTelephone"
                            label="联系方式"
                            rules={[{ required: true, message: '电话不能为空' },
                            ({ getFieldValue }) => ({
                                validator(rule, value) {
                                    var phoneReg = /^[1][3,4,5,7,8][0-9]{9}$/
                                    if (!value || phoneReg.test(value)) {
                                        return Promise.resolve();
                                    }
                                    return Promise.reject('请输入正确电话号码');
                                },
                            }),
                            ]}
                            hasFeedback
                        >
                            <Input />
                        </Form.Item>

                        <Form.Item
                            label="厂商地区"
                            name="area"
                            rules={[{ required: true, message: '标准地区' }]}
                        >
                            <Cascader
                                placeholder="请选择地区"
                                options={this.state.districtSource}
                                expandTrigger="hover"
                                style={{ width: '100%' }}
                            />
                        </Form.Item>

                        <Form.Item
                            label="详细地址"
                            name="specificAddr"
                            rules={[{ required: true, message: '详细地址' }]}
                        >
                            <Input placeholder="详细地址" style={{ width: '100%' }} />
                        </Form.Item>

                        <Form.Item
                            name="manufacturerIntroduction"
                            label="厂商简介"
                            rules={[
                                {
                                    required: true,
                                    message: '厂商简介必填',
                                },
                            ]}
                        >
                            <TextArea
                                autoSize={{ minRows: 4, maxRows: 12 }}
                            />
                        </Form.Item>
                        <Form.Item {...this.tailLayout}>
                            <Button type="primary" htmlType="submit" size="large">
                                确认修改
                            </Button>
                        </Form.Item>

                    </Form>
                </Card>
            </Spin>
        )
    }
}

export default withRouter(SpecificModifyManu)